package org.javagril.yuetong.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.javagril.yuetong.bean.Role;
import org.javagril.yuetong.bean.User;
import org.javagril.yuetong.service.LoginService;
import org.javagril.yuetong.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class LoginRealm extends AuthorizingRealm {
    @Autowired  /*注入对象*/
    LoginService loginService;
    @Autowired
    RoleService roleService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /*拿到 Session中的角色 而不是数据库中的*/
        /*拿到 用户角色存到user并转成User对象*/
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute("user");
        Role role = user.getRole();
        Set<String> roles = new HashSet<String>();
        roles.add(role.getRolename());
        return new SimpleAuthorizationInfo(roles);





    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String username = t.getUsername();
        User user = loginService.loadUserByAccount(username);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        /*返回的数据 保存到subject*/
        SecurityUtils.getSubject().getSession().setAttribute("user", user);


        return new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), ByteSource.Util.bytes(user.getAccount()), getName());
    }

    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("SHA-512");
        hashedCredentialsMatcher.setHashIterations(1024);
        return hashedCredentialsMatcher;
    }
}
